﻿using System;
using Microsoft.Rtc.Sip;

namespace PlusRemover
{
    public class PlusRemover
    {
        private bool _modifyFromHeader = false;
        private bool _modifyToHeader = false;

        public PlusRemover(bool modifyFromHeader, bool modifyToHeader)
        {
            _modifyFromHeader = modifyFromHeader;
            _modifyToHeader = modifyToHeader;
        }

        public void OnRequest(object sender,
            RequestReceivedEventArgs e)
        {
            // Enable simple proxy mode and disable forking, for better performance.
            e.Request.SimpleProxy = true;
            e.ServerTransaction.EnableForking = false;

            Console.WriteLine("Received dispatched INVITE.");

            if (_modifyFromHeader)
            {
                // Grab the From header, and strip the initial plus.
                Header fromHeader = e.Request.AllHeaders.FindFirst(Header.StandardHeaderType.From);
                fromHeader.Value = fromHeader.Value.Replace("tel:+", "tel:").Replace("sip:+", "sip:");

                Console.WriteLine("New From header: {0}", fromHeader.Value);
            }
            if (_modifyToHeader)
            {
                // Grab the To header, and strip the initial plus.
                Header toHeader = e.Request.AllHeaders.FindFirst(Header.StandardHeaderType.To);
                toHeader.Value = toHeader.Value.Replace("tel:+", "tel:").Replace("sip:+", "sip:");

                // Also strip the initial plus from the request URI.
                e.Request.Retarget(e.Request.RequestUri.Replace("tel:+", "tel:").Replace("sip:+", "sip:"));

                // Add in a phone context to the To URI and request URI so that normalization is performed.
                if (!toHeader.Value.Contains("phone-context"))
                {
                    toHeader.Value = toHeader.Value.Replace("@", ";phone-context=DefaultProfile@");
                }
                if (!e.Request.RequestUri.Contains("phone-context"))
                {
                    e.Request.Retarget(e.Request.RequestUri.Replace("@", ";phone-context=DefaultProfile@"));
                }

                Console.WriteLine("New To header and request URI: {0}", toHeader.Value);
            }

            // Send the request along.
            e.ServerTransaction.CreateBranch().SendRequest(
                e.Request);
        }
    }
}
